
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';

import { User } from '../models/User';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { LoginService } from './loginService';
import { Department } from '../models/Department';

@Injectable()
export class Loginauth {
  user: User;
  department: Department;
  constructor(public  router: Router, private loginService: LoginService) {}
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    // ActivatedRouteSnapshot包含了即将被激活的路由，而RouterStateSnapshot包含了该应用即将到达的状态。
    const url: string = state.url.slice(1);
    return this.checkLogin(url);
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.canActivate(route, state);
  }

  checkLogin(url?: string): Observable<boolean> {
    const user = this.loginService.user;
    if ( user ) {
      return of(true);
    }
    return this.loginService.getCurrent().pipe(map( res => {
        if (res.success) {
          this.loginService.user = res.res;
          return true;
        } else {
          // Store the attempted URL for redirecting
          this.loginService.redirectUrl = url;
          this.router.navigate(['/login']);
          return false;
        }
      }),
      catchError((err) => {
        console.log(err);
        this.router.navigate(['']);
        return of(false);
      }));
  }

  checkAdmin(): Observable<boolean> {
    const key = this.loginService.department.departmentKey;
    if ( key.indexOf('admin') !== -1 || key.indexOf('asset') !== -1 )  {
      return of(true);
    } else {
      return of(false);
    }
  }

  //是否为游客
  checkGuest(): Observable<boolean> {
    const key = this.loginService.department.departmentKey;
    if ( key.indexOf('guest') !== -1) {
      return of(true);
    } else {
      return of(false);
    }
  }

}
